<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="/">用户管理</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="7">
          <div class="grid-content bg-purple">
            <el-input
              placeholder="请输入内容"
              class="input-with-select"
              v-model="queryData.query"
              clearable
              @change="getUsersList"
            >
              <el-button slot="append" icon="el-icon-search" @click="getUsersList"></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="grid-content bg-purple">
            <el-button type="primary" @click="dialogVisible=true">添加用户</el-button>
          </div>
        </el-col>
      </el-row>
      <!-- 表格部份 -->
      <el-table :data="usersList">
        <!-- 表格里面索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <!-- 表格里面数据渲染列 -->
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <!-- 作用域插槽，这里接收数据它是用row传过来的 -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="changeUserStatus(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <!-- 操作部份 这里用作用域插槽是因为对应操作时候需要id，这个通过作用域插槽获取数据-->
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUser(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <!-- 这里用到了tooltip组件(文字提示) -->
            <el-tooltip effect="dark" content="角色替换" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRoles(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryData.pagenum"
        :page-sizes="[1, 3, 5, 6]"
        :page-size="queryData.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 新增用户对话框 -->
      <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @closed="resetDialog">
        <!-- 内容 -->
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveUserData">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改用户对话框 -->
      <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%">
        <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editRuleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户" prop="username">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserData">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
    <!-- 分配角色对话框 -->
    <el-dialog
  title="分配角色"
  :visible.sync="roleDialogVisible"
  width="50%">
  <!-- 内容部份 -->
  <p>用户姓名：{{role.username}}</p>
  <p>用户角色：{{role.role_name}}</p>
  <!-- 角色分配下拉框  v-model的值为当前被选中的el-option的 value 属性值-->
  请选择角色：<el-select v-model="roleValue" placeholder="请选择">
    <el-option
      v-for="item in roleList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>
  <span slot="footer" class="dialog-footer">
    <el-button @click="roleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="sureSetRoles">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      queryData: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      usersList: [],
      total: 0,
      dialogVisible: false,
      // 表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: undefined
      },
      // 增加用户对话框的验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入名字', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { min: 6, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '手机号不能为空' },
          { min: 11, message: 's手机必须为数字值' }
        ]
      },
      editDialogVisible: false,
      editForm: {
        id: undefined,
        username: '',
        email: '',
        mobile: undefined
      },
      editFormRules: {
        username: [
          { required: true, message: '请输入名字', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 2 到 5 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { min: 6, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '手机号不能为空' },
          { min: 6, message: 's手机必须为数字值' }
        ]
      },
      // 分配角色对话框的显示
      roleDialogVisible: false,
      // 点击分配角色，获取的对应用户信息
      role: {},
      // 所有角色列表
      roleList: [],
      // 对应的选中下拉框的id值
      roleValue: ''
    }
  },
  methods: {
    async getUsersList () {
      const { data: res } = await this.$http.get('users', {
        params: this.queryData
      })
      this.usersList = res.data.users
      this.total = res.data.total
    },
    // 点击选择不同条数，重新获取数据渲染列表
    handleSizeChange (val) {
      this.queryData.pagesize = val
      this.getUsersList()
    },
    // 点击选择不同页数，重新获取数据渲染列表
    handleCurrentChange (val) {
      this.queryData.pagenum = val
      this.getUsersList()
    },
    // 修改用户状态
    async changeUserStatus (userinfo) {
      await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
    },
    // 关闭对话框的时候重置
    resetDialog () {
      this.$refs.ruleForm.resetFields()
    },
    // 添加用户
    saveUserData () {
      this.$refs.ruleForm.validate(async (res) => {
        if (!res) return
        // eslint-disable-next-line no-unused-vars
        const { data: ret } = await this.$http.post('users', this.addForm)
        // 添加成功关闭对话框，且重新获取数据渲染列表
        this.dialogVisible = false
        this.getUsersList()
      })
    },
    // 修改用户
    async editUser (id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('users/' + id)
      this.editForm = res.data
    },
    // 修改用户提交
    editUserData () {
      // 先预前验证，验证通过后发送请求
      this.$refs.editRuleForm.validate(async (res) => {
        if (!res) return
        // eslint-disable-next-line no-unused-vars
        const { data: ret } = await this.$http.put(
          'users/' + this.editForm.id,
          this.editForm
        )
        // 添加成功关闭对话框，且重新获取数据渲染列表
        this.editDialogVisible = false
        this.getUsersList()
      })
    },
    // 删除用户
    async deleteUser (id) {
      const deleteData = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      if (deleteData === 'confirm') {
        const { data: res } = await this.$http.delete('users/' + id)
        if (res.meta.status !== 200) {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        } else {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getUsersList()
        }
      }
    },
    // 分配角色
    async setRoles (role) {
      this.role = role
      this.roleDialogVisible = true
      const { data: res } = await this.$http.get('roles')
      this.roleList = res.data
    },
    // 提交分配的角色
    async sureSetRoles () {
      await this.$http.put(`users/${this.role.id}/role`, { rid: this.roleValue })
      this.roleDialogVisible = false
      this.getUsersList()
    }
  },
  mounted () {
    this.getUsersList()
  }
}
</script>
